package com.baomidou.dynamic.datasource.config;

import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


public class JdbcDynamicDataSourceProvider extends AbstractDataSourceProvider implements DynamicDataSourceProvider {
    @Autowired
    @Qualifier("hikariDataSourceCreator")
    private DataSourceCreator dataSourceCreator;


    @Override
    public Map<String, DataSource> loadDataSources() {
        Map<String, DataSourceProperty> map = new HashMap<>();
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setUrl("jdbc:postgresql://192.168.10.111:5432/dev_base_platform?characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dataSourceProperty.setUsername("postgres");
        dataSourceProperty.setPassword("123456");
        dataSourceProperty.setDriverClassName("org.postgresql.Driver");
        map.put("primary",dataSourceProperty);
        return createDataSourceMap(map);
    }

    @Override
    protected Map<String, DataSource> createDataSourceMap(
            Map<String, DataSourceProperty> dataSourcePropertiesMap) {
        Map<String, DataSource> dataSourceMap = new HashMap<>(dataSourcePropertiesMap.size() * 2);
        for (Map.Entry<String, DataSourceProperty> item : dataSourcePropertiesMap.entrySet()) {
            DataSourceProperty dataSourceProperty = item.getValue();
            String poolName = dataSourceProperty.getPoolName();
            if (poolName == null || "".equals(poolName)) {
                poolName = item.getKey();
            }
            dataSourceProperty.setPoolName(poolName);
            dataSourceMap.put(item.getKey(), dataSourceCreator.createDataSource(dataSourceProperty));
        }
        return dataSourceMap;
    }
}

